package com.sdx.console.content.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.content.entity.EbookMain;
import com.sdx.console.content.service.EbookMainService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


/**
 * 电子书 接口
 */
@RequestMapping("/content/ebookMain")
@Controller
public class EbookMainController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(EbookMainController.class);
    private static final String MODEL = "/content/ebookMain";


    @Resource
	private EbookMainService ebookMainService;

	@Resource
	ResCloudFileService resCloudFileService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {

	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("content.ebookMain.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("content.ebookMain.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer bookId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        EbookMain ebookMain = ebookMainService.queryById(bookId);
        view.addObject("ebookMain", ebookMain);
		setPageParam(view,request);
		try {
			view.addObject("ebookMainJson", JacksonUtils.toJsonString(ebookMain,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("content.ebookMain.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
		view.addObject("ebookMain", new EbookMain());
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("content.ebookMain.query")
    @ResponseBody
    public JsonResult<PageQuery> list(EbookMain condtion)
    {
        PageQuery page = condtion.getPageQuery();
        ebookMainService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,EbookMain ebookMain,HttpServletRequest request
							,MultipartFile coverFile,MultipartFile urlFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/ebook/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(coverFile)) {
			try
			{
		        String coverFileNamePair = FileUtils.upload(subPath,coverFile);
		        String coverStoreFile = coverFileNamePair.split("::")[0];
		        coverStoreFile = subPath+coverStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+coverStoreFile,bucketName,coverStoreFile.substring(1));
				String coverUrl = "https://sdxcomm."+ ConfigService.ossDomain+coverStoreFile;
				ebookMain.setCover(coverUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,coverStoreFile,coverUrl,"a","电子书封面");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		if (!FileUtils.isEmptyFile(urlFile)) {
			try{
				bucketName = "sdxpri";
				subPath = "/file/ebook/"+dir+"/";
				String coverFileNamePair = FileUtils.upload(subPath,urlFile);
				String coverStoreFile = coverFileNamePair.split("::")[0];
				coverStoreFile = subPath+coverStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+coverStoreFile,bucketName,coverStoreFile.substring(1));
				String coverUrl = "https://sdxpri."+ ConfigService.ossDomain+coverStoreFile;
				ebookMain.setUrl(coverUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,coverStoreFile,coverUrl,"f","电子书地址");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);
		ebookMain.setUpdatedBy(user.getId().intValue());
		ebookMain.setUpdatedName(user.getName());
		ebookMain.setUpdatedTime(new Date());
    	if (isNew) {
			ebookMain.setCreatedBy(user.getId().intValue());
			ebookMain.setCreatedName(user.getName());
			ebookMain.setCreatedTime(new Date());
			ebookMainService.save(ebookMain);
		} else {
			ebookMainService.updateTemplate(ebookMain);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("content.ebookMain.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)EbookMain ebookMain,HttpServletRequest request
							,@RequestParam("coverFile") MultipartFile coverFile
							,@RequestParam("urlFile") MultipartFile urlFile
		)
    {

        return save(true,ebookMain,request
					,coverFile,urlFile
		);
    }

    @PostMapping("/update.json")
    @Function("content.ebookMain.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  EbookMain ebookMain,HttpServletRequest request
							,@RequestParam("coverFile") MultipartFile coverFile
							,@RequestParam("urlFile") MultipartFile urlFile
		) {
		return save(false,ebookMain,request
		,coverFile,urlFile
		);
    }



    @GetMapping("/view.json")
    @Function("content.ebookMain.query")
    @ResponseBody
    public JsonResult<EbookMain>queryInfo(Integer bookId) {
        EbookMain ebookMain = ebookMainService.queryById( bookId);
        return  JsonResult.success(ebookMain);
    }

    @PostMapping("/delete.json")
    @Function("content.ebookMain.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        ebookMainService.batchDelEbookMain(idList);
        return JsonResult.success();
    }


}
